<template>
  <CustomAgreementDialog btnName="同意协议并申请" ref="CustomAgreementDialogRef" @confirm="submit" @close="close">
    <div class="full-width" style="max-height: 52vh;">
      <div class="text-center" style="color: #999">个人信息共享授权协议</div>
        <div v-if="!webUrl" style="word-break: break-all" class="q-mt-sm">
          特别提醒：尊敬的客户，为维护您的合法权益，请你仔细阅读本授权书条款，并特别注意其中以黑体标注的条款。除非您已阅读并接受本授权书所有条款，否则请不要进行后续操作。您通过网络页面或客户端同意本授权书，即视为您已经充分阅读并理解本授权书所有条款同意承担由此带来的一切法律后果。
        </div>
        <div v-else class="q-mt-sm">
          <iframe ref="iframeRef" :src="dialog ? webUrl : ''" class="relative-position" style="border: none; outline: none; height: 200px; width: 100%; z-index: 4;"></iframe>
          <div class="absolute-full center" style="z-index: 1;" v-if="isShowIframeLoading" >
            <q-spinner color="primary" size="3em" />
          </div>
        </div>
        <div class="q-mt-lg" style="color: #666">特此授权</div>
        <div class="flex items-center no-wrap q-mt-lg" style="color: #666">
          <div class="" style="white-space: nowrap; width: 130px">授权人：</div>
          <div>{{ useAppStore().getAuthInfoData.realname }}</div>
        </div>
        <div class="flex items-center no-wrap q-mt-sm" style="color: #666">
          <div class="" style="white-space: nowrap; width: 130px">授权人身份证号码：</div>
          <div>{{ useAppStore().getAuthInfoData.idcard }}</div>
        </div>
    </div>
    <SignatureDialog ref="SignatureDialogRef" />
  </CustomAgreementDialog>
</template>

<script setup lang="ts">
import CustomAgreementDialog from 'src/components/customAgreementDialog/CustomAgreementDialog.vue'
import { CustomAgreementDialogInstance } from 'src/components/customAgreementDialog/CustomAgreementDialog'
import { ref, watchEffect } from 'vue';
import SignatureDialog from './SignatureDialog.vue'
import { Param, Show } from './Protocol';
import {useAppStore} from 'src/stores/app-store'
import { SignatureDialogInstance } from './SignatureDialog';
import { approveToPushApi } from 'src/api/info';
import { showLoadingToast } from 'vant';
import { useAfterHandler } from './afterHandler';
import { useRoute, useRouter } from 'vue-router';
import { useMechanismStore } from 'src/stores/mechanism-store';
import { getApiBOrderItemClickApi, getApiBOrderListApi } from 'src/api/merchant';
import { APIBItem } from 'src/types/apib';
const router = useRouter()
const route = useRoute()
const CustomAgreementDialogRef = ref<CustomAgreementDialogInstance>()
const webUrl = ref('');
const iframeRef = ref<HTMLIFrameElement>()
const isShowIframeLoading = ref(true)
const SignatureDialogRef = ref<SignatureDialogInstance>()

const loading = ref(false)
const emits = defineEmits(['close', 'nextHalf', 'againHalf'])
watchEffect(() => {
  if (!iframeRef.value) return;
  iframeRef.value.onload = () => {
    isShowIframeLoading.value = false
  }
})

const dialog = ref(false);
const param = ref<Param>()
const show:Show = (agreement, _param) => {
  webUrl.value = agreement?.length ? agreement : ''
  isShowIframeLoading.value = !!agreement?.length
  param.value = _param
  dialog.value = true;
  CustomAgreementDialogRef.value?.show('')
};

const close = () => {
  dialog.value = false;
  emits('close')
}
const submit = async () => {
  if (!param.value) return;

  loading.value = true
  const toast = showLoadingToast({
    iconSize: 50,
    forbidClick: true,
    duration: 0,
  });
  await approveToPushApi({
    orderId: param.value.orderId,
    itemOrderIds: param.value.itemOrderIds,
  }).finally(() => loading.value = false)
  if (param.value.approveUrl) {
    await getApiBOrderItemClickApi({ infoId: param.value.apibItem?.infoId, orderItemId: param.value.apibItem?.orderItemId });
    toast.close()
    emits('nextHalf')
    // useMechanismStore().resetHalfMatchData();
    window.location.href = param.value.approveUrl
    return;
  }
  toast.close()
  // const res = await initHalfMatchData();
  // if(res.halfMatchSuccess){
  //   emits('againHalf', res.item)
  //   close();
  //   return
  // }
  useAfterHandler(router, route).afterHandler(!!route.query.isApp)
  // SignatureDialogRef.value?.show(param.value)
};
const initHalfMatchData = async () => {
  const res = await getApiBOrderListApi<{ dataList: APIBItem[] }>({});
  if(res.data?.dataList.length > 0){
    useMechanismStore().setHalfMatchData(res.data?.dataList);
    return {
      halfMatchSuccess: true,
      item: res.data?.dataList
    }
  }
  return {
    halfMatchSuccess: false,
  }
}
defineExpose({ show, isShow: () => dialog.value  });
</script>
